// create by dplord at 2016-08-01 22:50

#include <stdio.h>
#include <string.h>

#define BUFFER_MAX 500
#include "stdlib.h"



#define TYPE_LEN 2
#define SIZE_LEN 4
/**
 * 复制文件100次, 每次前2个字节unsigned short代表类型,接着4个字节代表长度
 * unsigned long, 接着是文件内容
 */
void write_100f() {
    char *fname_des = "/home/dengpan/tmp/444/100-f.dat";
    char *fname_source = "/home/dengpan/tmp/444/1.jpg";
    int count = 100;
    FILE *fp_des, *fp_source;

    if((fp_source = fopen(fname_source, "rb")) == NULL || (fp_des = fopen(fname_des, "wb")) == NULL) {
        puts("error open file\n");
        exit(-1);
    }
    char buf[BUFFER_MAX];
    for (int i = 0; i < count; ++i) {
        unsigned short type = 1;
        fseek(fp_source , 0 , SEEK_END); // 指针移到文件末位
        unsigned long len = ftell(fp_source);  // 获得文件长度
        fseek(fp_source, 0, SEEK_SET);

        fwrite(&type, 1, TYPE_LEN, fp_des);
        fwrite(&len, 1, SIZE_LEN, fp_des);
        size_t bytes_read;
        while((bytes_read = fread(buf, 1, BUFFER_MAX, fp_source)) > 0) {
            printf("bytes_read = %d \n", bytes_read);
            fwrite(buf, 1, bytes_read, fp_des);
        }
        printf("%lu \n",len);
    }
}


/**
 * 读取100个文件
 */
void read_100f() {
    char *fname = "/home/dengpan/tmp/444/100-f.dat";
    FILE *fp;
    if((fp = fopen(fname, "rb")) == NULL) {
        printf("error when open file");
        exit(-1);
    }
    size_t bytes_read;

    int i = 0;
    char buf[BUFFER_MAX];
    int head_len = TYPE_LEN + SIZE_LEN;

    while(1) {
        unsigned short type;
        unsigned long len;

        size_t bytes1 = fread(&type, 1, TYPE_LEN, fp);
        size_t bytes2 = fread(&len, 1, SIZE_LEN, fp);

        printf("%hu %ld \n", type, len);
//        exit(-1);
        if(bytes1 != TYPE_LEN || bytes2 != SIZE_LEN) {
            printf("head读取错误  %d \n", ftell(fp));
            break;
        }

        size_t bytes_read = 0;
        char* fname_new = (char *)malloc(100);
        sprintf(fname_new, "/home/dengpan/tmp/444/new_%d.jpg", i ++);
        FILE *fp_new;
        if((fp_new = fopen(fname_new, "wb+")) == NULL) {
            puts("error write new image file");
            break;
        }

        while(len > 0) {
            size_t bytes3 = (len >= BUFFER_MAX) ? BUFFER_MAX : len;
            size_t bytes_read = fread(buf, 1, bytes3, fp);
            if(bytes_read != bytes3) {
                puts("read bytes error");
                exit(-1);
            }
            fwrite(buf, 1, bytes3, fp_new);
            len -= bytes3;
        }
    }
}

int main(int argc, char **arrv) {

//    write_100f();
    read_100f();
    return 0;
}


